package com.qf.listener;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson2.JSON;
import com.rabbitmq.client.Channel;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;


/**
 *
 * 接收消息 监听器
 * @author lixu
 */
@Component
@Slf4j
public class ReceverMessageListener {

    /**
     * 简单模式  接收消息
     */
    //@RabbitHandler
  //  @RabbitListener(queues = {"hello"})
    public void receiverMessage(String msg, Message message, Channel channel){

        try {
            System.out.println("接收到的消息:" + msg);

            //......................
            channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
        } catch (IOException e) {
            if (message.getMessageProperties().isRedelivered()){
                //拒绝处理此消息 删除队列
                try {
                    channel.basicReject(message.getMessageProperties().getDeliveryTag(),false);
                    log.error("当前消息已经投递{}", JSONObject.toJSON(message));
                    //通知人处理
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }else {
                try {
                    channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }

    }
    /**
     * 工作模式   接收消息
     */
    //@RabbitHandler
    @RabbitListener(queues = {"queue1"})
    public void workQueues1receiverMessage(String msg){

        System.out.println("1接收到的消息:" + msg);

        //......................
    }
    /**
     * 工作模式   接收消息
     */
    //@RabbitHandler
    @RabbitListener(queues = {"queue2"})
    public void workQueues2receiverMessage(String msg){

        System.out.println("2接收到的消息:" + msg);

        //......................
    }
    /**
     * 主题模式     接收消息
     */
    //@RabbitHandler
    @RabbitListener(queues = {"Q1"})
    public void workQ1receiverMessage(String msg){

        System.out.println("Q1接收到的消息:" + msg);

        //......................

    }
    /**
     * 主题模式     接收消息
     */
    //@RabbitHandler
    @RabbitListener(queues = {"Q2"})
    public void workQ2receiverMessage(String msg){

        System.out.println("Q2接收到的消息:" + msg);

        //......................
    }
}
